﻿using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using AForgeTest;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using WpfLockScreen.Common;
using Control = System.Windows.Forms.Control;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
namespace WpfLockScreen.Views
{
    /// <summary>
    /// LockWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LockWindow : Window
    {

        private int allSpan = 0;
        /// <summary>
        /// 上一次锁定时间
        /// </summary>
        private DateTime lastLock = DateTime.MinValue;
        /// <summary>
        /// 定时器 30秒
        /// </summary>
        private int SenSpan = 30;
        /// <summary>
        /// 锁屏时间
        /// </summary>
        private List<string> ListLockTime = new List<string>() { "12:00", "18:00", "19:00", "20:00", "21:00", "22:00" };
        KeyboardHook Hook = new KeyboardHook();
        DispatcherTimer Timer = new DispatcherTimer();

        public LockWindow()
        {
            InitializeComponent();
            //this.Icon = BitmapFrame.Create(new Uri("pack://application:,,,/app.ico", UriKind.RelativeOrAbsolute));
            this.pwd.Focus();

            this.ShowInTaskbar = false;//不显示任务栏上的图标

        }
        /// <summary>
        /// 页面准备完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            AutoStart();
            Hook.InstallHook(this.OnKeyPress);
            Timer.Interval = new TimeSpan(0, 0, SenSpan);
            Timer.Tick += Timer_Tick;
            Lock();
            new SocketServer();
            Pet();
        }
        /// <summary>
        /// 锁定，并关闭计时器
        /// </summary>
        private void Lock()
        {
            LockTitle.Text = "锁屏时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            //this.WindowState = WindowState.Maximized;
            if (this.Visibility == Visibility.Hidden)
                this.Visibility = Visibility.Visible;
            if (Timer.IsEnabled)
                Timer.Stop();
            CameraHelper.Start();
        }

        /// <summary>
        /// 提示
        /// </summary>
        private void Diag()
        {
            DiagView diag = new DiagView();
            diag.Show();
            Timer.Interval = CommStatic.RemindSpan;
        }

        /// <summary>
        /// 宠物
        /// </summary>
        private void Pet()
        {
            Pet diag = new Pet();
            diag.Show();
        }
        /// <summary>
        /// 解锁，并打卡计时器
        /// </summary>
        private void UnLock()
        {
            pwd.Password = string.Empty;
            if (this.Visibility == Visibility.Visible)
                this.Visibility = Visibility.Hidden;
            if (!Timer.IsEnabled)
                Timer.Start();
            CameraHelper.Stop();
        }
        /// <summary>
        /// 定时任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Tick(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            if (ListLockTime.Contains(now.ToString("HH:mm")))
            {
                Task.Factory.StartNew(() =>
                {
                    Dispatcher.BeginInvoke((Action)delegate ()
                    {
                        Lock();
                    });
                });
                return;
            }


            Task.Factory.StartNew(() =>
            {
                Dispatcher.BeginInvoke((Action)delegate ()
                {
                    LockTitle.Text = "锁屏时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                });
            });

            //allSpan += SenSpan;
            //if (allSpan >= 3600)
            //{
            //    allSpan = 0;
            //    Task.Factory.StartNew(() =>
            //    {
            //        Dispatcher.BeginInvoke((Action)delegate ()
            //        {
            //            Diag();
            //        });
            //    });
            //}
        }

        /// <summary> 
        /// 客户端键盘捕捉事件. 
        /// </summary> 
        /// <param name="hookStruct">由Hook程序发送的按键信息</param> 
        /// <param name="handle">是否拦截</param> 
        public void OnKeyPress(KeyboardHook.HookStruct hookStruct, out bool handle)
        {
            handle = false; //预设不拦截任何键 
            int keyData = hookStruct.vkCode;
            //截获alt+P 打开宠物 
            //if (hookStruct.vkCode == (int)Keys.P && (int)Control.ModifierKeys == (int)Keys.Alt)
            //{
            //    Pet();
            //    handle = true;
            //}
            //截获alt+L 快速锁定 
            if (hookStruct.vkCode == (int)Keys.L && (int)Control.ModifierKeys == (int)Keys.Alt)
            {
                Lock();
                handle = true;
            }
            // 截获左win(开始菜单键)
            if (hookStruct.vkCode == 91)
            {
                handle = true;
            }
            // 截获右win
            if (hookStruct.vkCode == 92)
            {
                handle = true;
            }
            //if ((int)Control.ModifierKeys == (int)Keys.Control)
            //{
            //    handle = true;
            //}

            //if ((int)Control.ModifierKeys == (int)Keys.Alt)
            //{
            //    handle = true;
            //    return;
            //}
            //截获Ctrl+Esc 
            if (hookStruct.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Control)
            {
                handle = true;
            }
            //截获alt+f4 
            if (hookStruct.vkCode == (int)Keys.F4 && (int)Control.ModifierKeys == (int)Keys.Alt)
            {
                handle = true;
            }
            //截获alt+tab 
            if (hookStruct.vkCode == (int)Keys.Tab && (int)Control.ModifierKeys == (int)Keys.Alt)
            {
                handle = true;
            }
            //截获F1 
            if (hookStruct.vkCode == (int)Keys.F1)
            {
                handle = true;
            }
            //截获任务管理器 Ctrl+Alt+Delete 
            if ((int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Alt + (int)Keys.Delete)
            {
                handle = true;
            }
            //如果键A~Z 
            if (hookStruct.vkCode >= (int)Keys.A && hookStruct.vkCode <= (int)Keys.Z)
            {
                //if (hookStruct.vkCode == (int)Keys.B)
                //    hookStruct.vkCode = (int)Keys.None; //设键为0 
                //handle = true;
            }
            Keys key = (Keys)hookStruct.vkCode;
            //LogHelper.GetLogHelper().Info("你按下:" + (key == Keys.None ? "" : key.ToString()));
        }

        /// <summary>
        /// 开机启动
        /// </summary>
        private void AutoStart()
        {
            string runName = System.IO.Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().GetName().Name);
            string path = CommStatic.TargetFullName + " " + CommStatic.Password;
            RegistryKey reg = null;
            reg = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
            if (reg == null)
            {
                reg = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            }
            reg.SetValue(runName, path);
            reg.Close();
        }

        /// <summary>
        /// 输入事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PasswordBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this.pwd.IsEnabled = false;
                if (pwd.Password == CommStatic.Password)
                {
                    this.Visibility = Visibility.Hidden;
                    this.UnLock();
                }
                else
                {
                    CameraHelper.CaptureImage(); 
                }
                Task.Factory.StartNew(() =>
                {
                    Task.Delay(2000).Wait();
                    Dispatcher.BeginInvoke((Action)delegate ()
                    {
                        this.pwd.IsEnabled = true;
                    });
                });
            }
        }
        /// <summary>
        /// 窗体关闭时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, CancelEventArgs e)
        {
            CameraHelper.Stop();
            e.Cancel = true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (Timer.IsEnabled)
            {
                Timer.Stop();
            }
            Hook.UninstallHook();
            Environment.Exit(0);
        }


    }
}
